//package com.aliyun.messagemgt.application.service.Impl.push.dingding.dingcompanygroup;
//
//import MsgBody;
//import MsgMiddleResult;
//import MsgRecordVO;
//import Receiver;
//import com.aliyun.messagemgt.application.service.DingCompanyGroupService;
//import com.aliyun.messagemgt.application.service.Impl.push.dingding.dingtalk.DingTalkTokenUtil;
//import com.aliyun.messagemgt.application.service.MsgPushChannel;
//import com.aliyun.messagemgt.common.constants.CommonConstant;
//import com.aliyun.messagemgt.common.constants.DingConstant;
//import com.aliyun.messagemgt.common.constants.push.PushResultEnum;
//import com.aliyun.messagemgt.dto.DingCompanyGroup;
//import com.aliyun.messagemgt.dto.PushChannelInfo;
//import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
//import com.aliyun.messagemgt.dto.in.DingDingOa;
//import com.dingtalk.api.DefaultDingTalkClient;
//import com.dingtalk.api.DingTalkClient;
//import com.dingtalk.api.request.OapiChatSendRequest;
//import com.dingtalk.api.response.OapiChatSendResponse;
//import com.taobao.api.ApiException;
//import org.apache.commons.collections.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.stream.Collectors;
//
//@Service
//public class DingCompanyGroupChannel implements MsgPushChannel {
//
//    private static Logger logger = LoggerFactory.getLogger(DingCompanyGroupChannel.class);
//
//    @Value("${dingding.dingTalk.send}")
//    private String dingTalkSend;
//    @Autowired
//    private DingCompanyGroupService dingCompanyGroupService;
//
//
//    @Override
//    public Integer getChannelType() {
//        return ChannelTypeEnum.DING_COMPANY_GROUP.getType();
//
//    }
//
//    @Override
//    public void push(PushChannelInfo pushChannelInfo, MsgRecordVO msgRecordVO) {
//        List<MsgMiddleResult> results = msgRecordVO.getResults();
//        if (results.size() > 0) {
//            return;
//        }
//        List<Receiver> users = msgRecordVO.getReceivers();
//        String chatId = pushChannelInfo.getChatId();
//        if(StringUtils.isEmpty(chatId)){
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(users, PushResultEnum.PUSH_COMPANY_GROUP_ERROR_CHATID);
//            results.add(msgMiddleResult);
//        }
//
//        DingCompanyGroup dingCompanyGroup = new DingCompanyGroup();
//        dingCompanyGroup.setChatId(chatId);
//        List<DingCompanyGroup> dataByInParam = dingCompanyGroupService.findDataByInParam(dingCompanyGroup);
//        if(CollectionUtils.isEmpty(dataByInParam)){
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(users, PushResultEnum.PUSH_COMPANY_GROUP_ERROR_INFO);
//            results.add(msgMiddleResult);
//        }
//        String corpId = dataByInParam.get(0).getCorpId();
//        String corpSecret = dataByInParam.get(0).getCorpSecret();
//        String token = DingTalkTokenUtil.getToken(corpId, corpSecret);
//        if (null == token) {
//            logger.error("{} 无法获取到对应的token", pushChannelInfo);
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(users, PushResultEnum.PUSH_TOKEN_INVALID);
//            results.add(msgMiddleResult);
//            return;
//        }
//        try {
//            sendMessageToChat(chatId,token,msgRecordVO);
//        } catch (Exception e) {
//            logger.error("钉钉企业群推送消息出现错误 {}", e.toString());
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(users, PushResultEnum.PUSH_ERROR);
//            results.add(msgMiddleResult);
//        }
//    }
//
//    public void  sendMessageToChat(String chatid,String token,MsgRecordVO msgRecordVO) throws ApiException {
//        List<MsgBody> contents = msgRecordVO.getContents();
//        if (CollectionUtils.isEmpty(contents)) {
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(msgRecordVO.getReceivers(), PushResultEnum.PUSH_MSG_INVALID);
//            msgRecordVO.getResults().add(msgMiddleResult);
//            return;
//        }
//        //发送消息到企业群
//        DingTalkClient clientMessage = new DefaultDingTalkClient(dingTalkSend);
//        OapiChatSendRequest reqMessage = new OapiChatSendRequest();
//        reqMessage.setChatid(chatid);
//        OapiChatSendResponse response = getDingChatResponse(chatid,token,msgRecordVO,clientMessage);
//        if (response.isSuccess()) {
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(msgRecordVO.getReceivers(), PushResultEnum.PUSH_SUCCESS);
//            msgRecordVO.getResults().add(msgMiddleResult);
//        } else {
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(msgRecordVO.getReceivers(),
//                    PushResultEnum.PUSH_ROBOT_ERROR_CODE.getErrorCode(), response.getErrmsg());
//            msgRecordVO.getResults().add(msgMiddleResult);
//        }
//    }
//
//    /**
//     * 封装消息返回结果
//     *
//     * @param reveivers             接收人
//     * @param pushResultCode        推送状态码
//     * @param pushResultDescription 推送结果描述
//     */
//    private MsgMiddleResult generateMsgMiddleResult(List<Receiver> reveivers, Integer pushResultCode, String pushResultDescription) {
//        return new MsgMiddleResult()
//                .setReceivers(reveivers)
//                .setPushResultCode(pushResultCode)
//                .setPushResultDescription(pushResultDescription);
//    }
//
//    private MsgMiddleResult generateMsgMiddleResult(List<Receiver> reveivers, PushResultEnum pushResult) {
//        return new MsgMiddleResult()
//                .setReceivers(reveivers)
//                .setPushResultCode(pushResult.getErrorCode())
//                .setPushResultDescription(pushResult.getDescription());
//    }
//
//    private OapiChatSendRequest buildActioncardRequest(MsgRecordVO msgRecordVO) {
//        List<MsgBody> contents = msgRecordVO.getContents();
//        List<MsgBody> actionCardContents = contents.stream().filter(s -> DingConstant.ACTIONCARD.equals(s.getType())).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(actionCardContents)) {
//            return null;
//        }
//
//        OapiChatSendRequest.Msg msg = new OapiChatSendRequest.Msg();
//        OapiChatSendRequest.ActionCard actioncard = new OapiChatSendRequest.ActionCard();
//        actioncard.setTitle(msgRecordVO.getMsgTitle());
//        actioncard.setMarkdown(msgRecordVO.getMsgContent());
//        if (actionCardContents.size() == 1) {
//            MsgBody msgBody = actionCardContents.get(0);
//            actioncard.setSingleTitle(msgBody.getContent());
//            actioncard.setSingleUrl(msgBody.getMessageUrl());
//        } else {
//            actioncard.setBtnOrientation(msgRecordVO.getBtnOrientation());
//            OapiChatSendRequest.BtnJson btn = null;
//            List<OapiChatSendRequest.BtnJson> btns = new ArrayList<>();
//            for (MsgBody msgBody : actionCardContents) {
//                btn = new OapiChatSendRequest.BtnJson();
//                btn.setTitle(msgBody.getContent());
//                btn.setActionUrl(msgBody.getMessageUrl());
//                btns.add(btn);
//            }
//            actioncard.setBtnJsonList(btns);
//        }
//        msg.setActionCard(actioncard);
//        msg.setMsgtype(DingConstant.ACTION_CARD);
//
//        OapiChatSendRequest request = new OapiChatSendRequest();
//        request.setMsg(msg);
//        return request;
//    }
//
//    private OapiChatSendRequest buildOaRequest(MsgRecordVO msgRecordVO) {
//        List<MsgBody> contents = msgRecordVO.getContents();
//        List<MsgBody> actionCardContents = contents.stream().filter(s -> DingConstant.OA.equals(s.getType())).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(actionCardContents)) {
//            return null;
//        }
//        DingDingOa dingDingOa = msgRecordVO.getDingDingOa();
//        if(null == dingDingOa){
//            MsgMiddleResult msgMiddleResult = generateMsgMiddleResult(msgRecordVO.getReceivers(),
//                    PushResultEnum.PUSH_COMPANY_GROUP_ERROR_OA);
//            msgRecordVO.getResults().add(msgMiddleResult);
//            return null;
//        }
//
//        OapiChatSendRequest.Form form = null;
//        List<OapiChatSendRequest.Form> forms = new ArrayList<>();
//        for (MsgBody msgBody : actionCardContents) {
//            form = new OapiChatSendRequest.Form();
//            form.setKey(msgBody.getKey());
//            form.setValue(msgBody.getContent());
//            forms.add(form);
//        }
//
//        OapiChatSendRequest.Rich rich = new OapiChatSendRequest.Rich();
//        rich.setNum(dingDingOa.getBodyRichNum());
//        rich.setUnit(dingDingOa.getBodyRichUnit());
//
//        OapiChatSendRequest.Body body = new OapiChatSendRequest.Body();
//        body.setTitle(msgRecordVO.getMsgTitle());
//        body.setContent(msgRecordVO.getMsgContent());
//        body.setForm(forms);
//        body.setFileCount(String.valueOf(forms.size()));
//        body.setImage(dingDingOa.getBodyImage());
//        body.setAuthor(dingDingOa.getBodyAuthor());
//        body.setRich(rich);
//
//        OapiChatSendRequest.Head head = new OapiChatSendRequest.Head();
//        head.setBgcolor(dingDingOa.getHeadBgcolor());
//        head.setText(dingDingOa.getHeadText());
//
//        OapiChatSendRequest.Msg msg = new OapiChatSendRequest.Msg();
//        OapiChatSendRequest.Oa oa = new OapiChatSendRequest.Oa();
//        oa.setMessageUrl(dingDingOa.getMessageUrl());
//        oa.setPcMessageUrl(dingDingOa.getPcMessageUrl());
//        oa.setHead(head);
//        oa.setBody(body);
//
//        msg.setOa(oa);
//        msg.setMsgtype(DingConstant.OA);
//
//        OapiChatSendRequest request = new OapiChatSendRequest();
//        request.setMsg(msg);
//        return request;
//    }
//
//    private OapiChatSendResponse getDingChatResponse(String chatid, String token, MsgRecordVO msgRecordVO, DingTalkClient client) throws ApiException {
//        OapiChatSendResponse response = null;
//        OapiChatSendRequest request = new OapiChatSendRequest();
//        request.setChatid(chatid);
//        request = buildActioncardRequest(msgRecordVO);
//        if (null != request) {
//            request.setChatid(chatid);
//            response = client.execute(request,token);
//        }
//        request = buildOaRequest(msgRecordVO);
//        if (null != request) {
//            request.setChatid(chatid);
//            response = client.execute(request, token);
//            request = null;
//        }
//        OapiChatSendRequest.Msg msg = null;
//        List<MsgBody> contents = msgRecordVO.getContents();
//        for (MsgBody msgBody : contents) {
//            String type = msgBody.getType();
//            if (DingConstant.ACTIONCARD.equals(type) || DingConstant.OA.equals(type)) {
//                continue;
//            }
//            request = new OapiChatSendRequest();
//            request.setChatid(chatid);
//            switch (type) {
//                case CommonConstant.TEXT:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.Text text = new OapiChatSendRequest.Text();
//                    text.setContent(msgBody.getContent());
//                    msg.setText(text);
//                    break;
//                case DingConstant.LINK:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.Link link = new OapiChatSendRequest.Link();
//                    link.setTitle(msgRecordVO.getMsgTitle());
//                    link.setText(msgBody.getContent());
//                    link.setPicUrl(msgBody.getPicUrl());
//                    link.setMessageUrl(msgBody.getMessageUrl());
//                    msg.setLink(link);
//                    break;
//                case DingConstant.MARKDOWN:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.Markdown markdown = new OapiChatSendRequest.Markdown();
//                    markdown.setTitle(msgRecordVO.getMsgTitle());
//                    markdown.setText(msgBody.getContent());
//                    msg.setMarkdown(markdown);
//                    break;
//                case DingConstant.IMAGE:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.Image image = new OapiChatSendRequest.Image();
//                    image.setMediaId(msgBody.getContent());
//                    msg.setImage(image);
//                    break;
//                case DingConstant.FILE:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.File file = new OapiChatSendRequest.File();
//                    file.setMediaId(msgBody.getContent());
//                    msg.setFile(file);
//                    break;
//                case DingConstant.VOICE:
//                    msg = new OapiChatSendRequest.Msg();
//                    OapiChatSendRequest.Voice voice = new OapiChatSendRequest.Voice();
//                    voice.setMediaId(msgBody.getContent());
//                    voice.setDuration(msgBody.getDuration());
//                    msg.setVoice(voice);
//                    break;
//                default:
//                    break;
//            }
//            if(null != msg){
//                msg.setMsgtype(type);
//                request.setMsg(msg);
//                response = client.execute(request,token);
//            }
//        }
//        return response;
//    }
//}
